package com.linkdood.app.web.rest;

import com.linkdood.app.constants.SynchronizeConstants;
import com.linkdood.app.domain.ThirdParty;
import com.linkdood.app.exception.InvalidParamException;
import com.linkdood.app.service.*;
import com.linkdood.app.service.impl.DdioSynchronize;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 接收同步信息
 *
 * @author YunJ
 */
@Slf4j
@RestController
@RequestMapping("/api/ddio")
public class SyncMessageResource {
    private final SyncMessageService syncMessageService;

    private final ThirdPartyService thirdPartyService;

    private final DdioSynchronize ddioSynchronize;

    private final MessageTemplateService messageTemplateService;

    private static final String DDIO_EVENT_TYPE_UPDATE_USER = "1";
    private static final String DDIO_EVENT_TYPE_UPDATE_ORG = "2";

    public SyncMessageResource(SyncMessageService syncMessageService,
                               DdioSynchronize ddioSynchronize,
                               ThirdPartyService thirdPartyService,
                               MessageTemplateService messageTemplateService) {
        this.syncMessageService = syncMessageService;
        this.ddioSynchronize = ddioSynchronize;
        this.thirdPartyService = thirdPartyService;
        this.messageTemplateService = messageTemplateService;
    }


    /**
     * dood 服务器消息，认证接口
     */
    @GetMapping("/message")
    public ResponseEntity<?> messageTest(@RequestParam String msg) {
        log.debug("message validate msg : {}", msg);
        return ResponseEntity.ok(syncMessageService.validateToken(msg));
    }

    /**
     * 接收 dood 服务器消息
     * 每个公司应该单独配置一个 url, 这里为系统默认公司
     * fixme ： 如果要修改这里的 url， 则要同步更新 {@link com.linkdood.app.web.rest.SystemResource#getWebConfig} 中的 serviceUrl
     */
    @RequestMapping("/message")
    public void getNotice(@RequestBody Map<String, Object> map) {
        log.info("message : get user sync...");
        for (String key : map.keySet()) {
            log.info("key = {}, value = {}", key, map.get(key));
        }
        String messageTypeKey = "messageType";
        String messageTypeValue = "event";

        if (!map.containsKey(messageTypeKey) && !messageTypeValue.equals(map.get(messageTypeKey))) {
            dealMessage(map);
        }
        if (!map.containsKey(messageTypeKey) || !messageTypeValue.equals(map.get(messageTypeKey)) ||
                !map.containsKey("event") || !"synchronize".equals(map.get("event")) ||
                !map.containsKey("eventValue")) {
            log.error("not synchronize message");
        }

        ThirdParty thirdParty = thirdPartyService.getDefaultThirdParty();
        // 事件值，1：用户，2：组织机构
        String eventValue = map.get("eventValue").toString();
        if (DDIO_EVENT_TYPE_UPDATE_USER.equals(eventValue)) {
            ddioSynchronize.syncUser(SynchronizeConstants.SYNC_TYPE_INCREMENT, thirdParty);
        } else if (DDIO_EVENT_TYPE_UPDATE_ORG.equals(eventValue)) {
            ddioSynchronize.syncOrg(SynchronizeConstants.SYNC_TYPE_INCREMENT, thirdParty);
        }
    }

    private void dealMessage(Map<String, Object> map) {
        if (map == null) {
            throw new InvalidParamException("map");
        }

        Object object = map.get("message");
        Map<String, Object> message = (Map<String, Object>) object;
        this.checkMessageMap(message);
        if (StringUtils.isBlank(message.get("bId").toString())) {
            throw new InvalidParamException("bId is empty");
        }
        String bId = message.get("bId").toString();
        String mToken = message.get("mToken").toString();
        Map<String, Object> eventData = (Map<String, Object>) message.get("eventData");
        String eventType = eventData.get("eventType").toString();

        log.info("id : {}, mToken : {}, eventType : {}", bId, mToken, eventType);
        messageTemplateService.dealMessageResult(bId, mToken, eventType);
    }

    public void checkMessageMap(Map<String, Object> message) {

        if (!message.containsKey("bId") || message.get("bId") == null) {
            throw new InvalidParamException("bId");
        }

        if (!message.containsKey("mToken") || message.get("mToken") == null) {
            throw new InvalidParamException("mToken");
        }

        if (!message.containsKey("eventData") || message.get("eventData") == null) {
            throw new InvalidParamException("eventData");
        }

        Map<String, Object> eventData = (Map<String, Object>) message.get("eventData");
        if (!eventData.containsKey("eventType") || eventData.get("eventType") == null) {
            throw new InvalidParamException("eventType");
        }
    }
}
